package com.gitee.ywj1352.算法.真实;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 组合总合II_40 {

    int ans;


    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        ans = target;
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        boolean[] status = new boolean[candidates.length];
        Arrays.sort(candidates);
        helper(candidates, status, 0, res, 0);
        return res;
    }

    public void helper(int[] arr, boolean[] status, int depth,
                       List<List<Integer>> res, int target) {
        if (target == ans) {
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < status.length; i++) {
                if (status[i]) list.add(arr[i]);
            }
            res.add(list);
            return;
        }
        for (int i = depth; i < arr.length; i++) {
            if (i > 0 && arr[i] == arr[i - 1] && !status[i - 1])  ;
            if (!status[i]) {
                if(target + arr[i] > ans) {
                    break;
                }
                status[i] = true;
                helper(arr, status, i + 1, res, target + arr[i]);
                status[i] = false;
            }
        }
    }


    public static void main(String[] args) {

        组合总合II_40 zu = new 组合总合II_40();
        int[] arr = {10, 1, 2, 7, 6, 1, 5};
        List<List<Integer>> lists = zu.combinationSum2(arr, 8);
        for (List<Integer> re : lists) {
            System.out.println(re);
        }
    }
}
